package com.lhm.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelImportEntity;
import com.lhm.common.Result;
import com.lhm.entity.Student;
import com.lhm.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: lhm
 * @Date: 2020/12/4 15:55
 * 4
 */
@Controller
@Slf4j
public class StudentController {

    @Autowired
    StudentService studentService;
    @Value("${upload.dir}")
    private String filePath;

    @RequestMapping({"/", "/index"})
    public String stuList() {
        return "studentList";
    }

    /**
     * 导入Excel
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            log.info(originalFilename);
            ImportParams params = new ImportParams();
            //标题行，如果没有就不填，否则导入时数据会变成null
            params.setTitleRows(1);
            //头行，例如：姓名、地址、联系方式  这些字段所占的行，占几行就填几
            params.setHeadRows(1);
            //执行导入方法，返回的是一个集合（将Excel中的数据变成了pojo组成的集合）
            List<Student> students = ExcelImportUtil.importExcel(file.getInputStream(), Student.class, params);
            //调用getImgName方法获取图片名
            List<Student> list = getImgName(students);
            students.forEach(System.out::println);
            //调用方法将数据保存到数据库
            studentService.saveBatch(list);
            return Result.success("上传成功", originalFilename);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("上传失败");
        }
    }

    /**
     * 导出excel
     * @param response
     * @throws IOException
     */
    @RequestMapping("/export")
    public void exportExcel(HttpServletResponse response) throws IOException {
        //查询出要导出的数据
        List<Student> students = studentService.findAll();
        //修改图片的地址（改成实际的路径）
        students.forEach(student -> {
            student.setPhoto(filePath + student.getPhoto());
        });
        //生成Excel
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("学生信息列表", "学生信息"), Student.class, students);
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("学生信息.xls", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.close();
        workbook.close();
    }

    /**
     * 前端获取信息用于展示，这里不做分页了
     * @return
     */
    @RequestMapping("/findAll")
    @ResponseBody
    public Map<String, Object> findAll() {
        List<Student> all = studentService.findAll();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "获取成功");
        map.put("count", all.size());
        map.put("data", all);
        return map;
    }

    /**
     * 获取图片名
     * @param students
     * @return
     */
    public List<Student> getImgName(List<Student> students) {
        students.forEach(student -> {
            String fileName = student.getPhoto().substring(student.getPhoto().lastIndexOf("\\") + 1);
            student.setPhoto(fileName);
        });
        return students;
    }
}
